package com.learn.threadpool.service.impl;

import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.learn.threadpool.domain.Order;
import com.learn.threadpool.mapper.OrderMapper;
import com.learn.threadpool.service.AsyncService;
import com.learn.threadpool.service.OrderService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CountDownLatch;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Resource
    private AsyncService asyncService;


    @Override
    public int multiThread() {
        List<Order> orderList = this.baseMapper.selectList(new QueryWrapper<>());
        // 测试每100条数据插入开一个线程
        List<List<Order>> lists = ListUtil.split(orderList, 100);
        CountDownLatch countDownLatch = new CountDownLatch(lists.size());
        for (List<Order> listSub : lists) {
            asyncService.executeAsync(listSub, this.baseMapper, countDownLatch);
        }
        try {
            // 保证之前的所有的线程都执行完成，才会走下面的；
            countDownLatch.await();
            // 这样就可以在下面拿到所有线程执行完的集合结果
        } catch (Exception e) {
            log.error("阻塞异常：" + e.getMessage());
        }
        return orderList.size();
    }


}
